package top.leyi.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import top.leyi.entity.user.User;
import top.leyi.exception.TokenException;
import top.leyi.mapper.UserMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Allen
 * @desc   token身份验证拦截器
 */

@Component("TokenInterceptor")
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /*
         * 如果是token方法则放行
         */
        String url = request.getRequestURI();

             /*
               从redis中查看是否存在这个token
              */
            String token = request.getParameter("token");

            if (token != null) {
                if (redisTemplate.opsForSet().isMember("token", token)) {

                    return true;
                } else {
                    User user  = userMapper.queryUserInfo(token);

                    if (user != null ) {
                        redisTemplate.opsForSet().add("token", token);
                        return true;
                    }
                }
            }
             throw new  TokenException();
    }
}